package com.liao.library.ability;

import com.liao.library.lifecycle.viewmodel.ViewModelStore;
import com.liao.library.lifecycle.viewmodel.ViewModelStoreOwner;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.Lifecycle;
import ohos.aafwk.ability.LifecycleStateObserver;
import ohos.aafwk.content.Intent;

public abstract class ComponentAbility extends Ability implements ViewModelStoreOwner {

    private ViewModelStore mViewModelStore;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);

        getLifecycle().addObserver(new LifecycleStateObserver() {
            @Override
            public void onStateChanged(Lifecycle.Event event, Intent intent) {
                if (event == Lifecycle.Event.ON_STOP) {
                    getViewModelStore().clear();
                }
            }
        });
    }

    @Override
    public ViewModelStore getViewModelStore() {
        if (getAbilityPackage() == null) {
            throw new IllegalStateException("Your ability is not yet attached to the "
                    + "AbilityPackage instance. You can't request ViewModel before onStart call.");
        }

        if (mViewModelStore == null) {
            mViewModelStore = new ViewModelStore();
        }
        return mViewModelStore;
    }
}
